# -*- coding: utf-8 -*-
import os


import os2
'''
考虑如下path:

uri格式                                         本地格式或解释
file://d:/app/                            d:\app
file://chen-peng/h                        \\chen-peng\h
pop3://chen:password@gmail.com/a/b.txt    在chen的gmail邮箱中的/a/b.txt
'''


class Path2(object):
     
    ROOT = None #由于不能自身初始化类属性所以在下面初始化 
    def __init__(self,device,segments):
        '''client请使用path.Path()构造'''
        assert segments is not None
        self._segments = segments
        self._device=device

    def append(self,path):
        segments=self._segments[:]
        if isinstance(path,Path2):
            segments.extend(path._segments)
        else:
            segments.append(path)
        return Path2(self._device,segments)
    
    def getSegments(self):
        return self._segments[:]
    
    def getSegment(self,index):
        return self._segments[index]
    
    def getSegmentsCount(self):
        return len(self._segments)
    
    def getParent(self):
        if self == Path2.ROOT:
            return None
        return Path2(self._device,self._segments[:-1])
    
    def __cmp__(self,other):
        return cmp(self._segments ,other._segments
)     
    def __hash__(self):
        return hash(str(self))
    
    def lastSegment(self):
        if self == Path2.ROOT:
            return None
        return self._segments[-1]
    
    def getLastSegment(self):
        if self == Path2.ROOT:
            return None
        return self._segments[-1]
    
    def removeLastSegments(self,count):
        assert count <= self.getSegmentsCount()
        return Path2(self._device,self._segments[:-count])
    
    def removeFirstSegments(self,count):
        assert count <= self.getSegmentsCount()
        return Path2(self._device,self._segments[count:])
    
    def getUriWith(self,schame):
        if self._device!='':
            return '%s://%s/%s' % (schame,self._device,_SEPARATOR.join(self._segments))   
        else:
            return '%s://%s' % (schame,_SEPARATOR.join(self._segments))   
        
    def __str__(self):
        return self._device+_ROOT_STRING+_SEPARATOR.join(self._segments)
    
    #override
    def __repr__(self):
        return str(self)
    
    @staticmethod
    def parse(str):
        if str == _ROOT_STRING:
            return ROOT
    
        device,path = os.path.splitdrive(str)
        return Path2(device,os2.splitPath(path))

_ROOT_STRING = '/'
_SEPARATOR = '/'

Path2.ROOT = Path2('',[])
